//express_demo.js 文件
var express = require('express');
var app = express();

var bodyParser = require('body-parser');
// 创建 application/json 解析
var jsonParser = bodyParser.json();
// 创建数据库连接
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/wsm";
 
app.get('/api/getusers',(req,res) => {
    MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true  }, function(err, db) {
        if (err) {
            console.log( err );  
            var result = {
                status: 0,
                message: "fail",
                data: err
             }
            res.jsonp(result);
        }
        console.log("数据库连接成功");       
        var dbase = db.db("wsm");   
        dbase.collection("users").find({}).toArray(function(err, data) { // 返回集合中所有数据
            if (err) {
                console.log( err );  
                var result = {
                    status: 0,
                    message: "fail",
                    data: err
                 }
                res.jsonp(result);
            }
            console.log(data);
              
            var result = {
                status: 1,
                message: "success",
                data: data
             }
            res.jsonp(result);
            db.close();
        })
    })
}) 
app.get('/api/getuser',(req,res) => {
    MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true  }, function(err, db) {
        if (err) {
            console.log( err );  
            var result = {
                status: 0,
                message: "fail",
                data: err
             }
            res.jsonp(result);
        }
        console.log("数据库连接成功");       
        var dbase = db.db("wsm");   
        
        var whParam=req.query.UserName;
        var whereStr = {"username" : whParam};  // 查询条件
        dbase.collection("users").find(whereStr).toArray(function(err, data) { // 返回集合中所有数据
            if (err) {
                console.log( err );  
                var result = {
                    status: 0,
                    message: "fail",
                    data: err
                 }
                res.jsonp(result);
            }
            console.log(data);

            if(data.length>0)
            {
                var result = {
                    status: 1,
                    message: "success",
                    data: data
                 }
                res.jsonp(result);
            }else
            {
                var result = {
                    status: 0,
                    message: "fail",
                    data: "用户不存在"
                 }
                res.jsonp(result);
            }
            db.close();
        })
    })
}) 
app.get('/api/getuserpage',(req,res) => {
    MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true  }, function(err, db) {
        if (err) {
            console.log( err );  
            var result = {
                status: 0,
                message: "fail",
                data: err
             }
            res.jsonp(result);
        }
        console.log("数据库连接成功");       
        var dbase = db.db("wsm");   
        
        var s=parseInt(req.query.skip);
        var l=parseInt(req.query.limit);
        //.skip()跳过
        //.limit()取指定数量记录
        //.sort()排序 ：1升序-1降序
        var mysort = { "roleid": -1 };
        dbase.collection("users").find({}).skip(s).limit(l).sort(mysort).toArray(function(err, data) { // 返回集合中所有数据
            if (err) {
                console.log( err );  
                var result = {
                    status: 0,
                    message: "fail",
                    data: err
                 }
                res.jsonp(result);
            }
            console.log(data);

            if(data.length>0)
            {
                var result = {
                    status: 1,
                    message: "success",
                    data: data
                 }
                res.jsonp(result);
            }else
            {
                var result = {
                    status: 0,
                    message: "fail",
                    data: "用户不存在"
                 }
                res.jsonp(result);
            }
            db.close();
        })
    })
}) 
app.get('/api/getuserrole',(req,res) => {
    MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true  }, function(err, db) {
        if (err) {
            console.log( err );  
            var result = {
                status: 0,
                message: "fail",
                data: err
             }
            res.jsonp(result);
        }
        console.log("数据库连接成功");       
        var dbase = db.db("wsm");   
        var whParam=req.query.UserName
        
        //match实现过滤
        //lookup实现左连接        
        dbase.collection("users").aggregate([
            { $match : 
                {"username" : whParam}
            }, 
            {$lookup:
               {
                 from: 'roles',            // 右集合
                 localField: 'roleid',    // 左集合 join 字段
                 foreignField: 'roleid',         // 右集合 join 字段
                 as: 'userrole'           // 新生成字段（类型array）
               }
            }
            ]).toArray(function(err, data) { // 返回集合中所有数据
            if (err) {
                console.log( err );  
                var result = {
                    status: 0,
                    message: "fail",
                    data: err
                 }
                res.jsonp(result);
            }
            console.log(data);

            if(Array.isArray(data) && data.length>0)
            {                
                var result = {
                    status: 1,
                    message: "success",
                    data: data
                 }
                res.jsonp(result);
            }else
            {
                var result = {
                    status: 0,
                    message: "fail",
                    data: "用户不存在"
                 }
                res.jsonp(result);
            }
            db.close();
        })
    })
}) 
app.post('/api/adduser',jsonParser,(req,res) => {
    MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true  }, function(err, db) {
        if (err) {
            console.log( err );  
            var result = {
                status: 0,
                message: "fail",
                data: err
             }
            res.jsonp(result);
        }
        console.log("数据库连接成功");       
        var dbase = db.db("wsm");   
        var newUser = req.body;

        // {
        //     "_id": "5c1ca2363298b2d7015ce1e",
        //     "username": "aaaaaa",
        //     "password": "7c4a8d09ca3762af61e59520943dc26494f8941b",
        //     "roleid": 6,
        //     "email": "xx@126.com",
        //     "description": "我是测试信息",
        //     "team": "所有",
        //     "xzqdm": [
        //     ],
        //     "xzqmc": [
        //     ]
        //     }

        //console.log(req.body.username);
        
        //insertMany插入多条
        dbase.collection("users").insertOne(newUser,function(err, data) {

            if (err) {
                console.log( err );  
                var result = {
                    status: 0,
                    message: "fail",
                    data: err
                 }
                res.jsonp(result);
            }
            var result = {
                status: 1,
                message: "success",
                data: data
             }
            res.jsonp(result);
            //console.log(data);

        })
    })
}) 

app.post('/api/updateuser',jsonParser,(req,res) => {
    MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true  }, function(err, db) {
        if (err) {
            console.log( err );  
            var result = {
                status: 0,
                message: "fail",
                data: err
             }
            res.jsonp(result);
        }
        console.log("数据库连接成功");       
        var dbase = db.db("wsm");   

        var whereStr = {"username":req.body.username};  // 查询条件
        var updateStr = {$set: { "email" : req.body.email}};
           
        //updateone
        //updateMany更新多条
        dbase.collection("users").updateMany(whereStr, updateStr,function(err, data) {

            if (err) {
                console.log( err );  
                var result = {
                    status: 0,
                    message: "fail",
                    data: err
                 }
                res.jsonp(result);
            }
            if(data.result.nModified>0)
            {
                var result = {
                    status: 1,
                    message: "success",
                    data: data
                 }
                res.jsonp(result);
                console.log("更新用户信息成功"+data.result.nModified+"条");
            }else
            {
                var result = {
                    status: 0,
                    message: "fail",
                    data: data
                 }
                res.jsonp(result);
                console.log("更新用户信息失败，用户不存在");
            }
            
            db.close();

        })
    })
}) 

app.post('/api/deleteuser',jsonParser,(req,res) => {
    MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true  }, function(err, db) {
        if (err) {
            console.log( err );  
            var result = {
                status: 0,
                message: "fail",
                data: err
             }
            res.jsonp(result);
        }
        console.log("数据库连接成功");       
        var dbase = db.db("wsm");   

        var whereStr = {"username":req.body.username};  
           
        //deleteOne
        //deleteMany删除多条
        dbase.collection("users").deleteMany(whereStr,function(err, data) {

            if (err) {
                console.log( err );  
                var result = {
                    status: 0,
                    message: "fail",
                    data: err
                 }
                res.jsonp(result);
            }
            if(data.result.n>0)
            {
                var result = {
                    status: 1,
                    message: "success",
                    data: data
                 }
                res.jsonp(result);
                console.log("删除用户信息成功"+data.result.n+"条");
            }else
            {
                var result = {
                    status: 0,
                    message: "fail",
                    data: data
                 }
                res.jsonp(result);
                console.log("删除用户信息失败");
            }
           
            db.close();

        })
    })
}) 

var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例，访问地址为 http://%s:%s", host, port)
 
})
